<?php
/**
* Yapp update wrapper
*/

class Update extends operationsBase
{
    // Own for select
    private $fieldsAndValues = false;

    // Set table
    public function table($tableName, $database = false)
    {
        return $this->_from($tableName, $database);
    }

    // Set fields
    public function set($values)
    {
        if ($this->killChaining) return $this;
        else
        {
            if (is_array($values) && (!empty($values)))
            {
                foreach ($values as $fieldName => $fieldValue)
                {
                    $field = $this->getTableAndField($fieldName);
                    if (empty($field['table']))
                    {
                        $table = $this->tableName;
                    }
                    if ($table == $this->tableName)
                    {
                        $this->validateFieldNameAndValue($fieldName, $fieldValue);
                        if (($fieldName !== false) && ($fieldValue !== false))
                        {
                            $this->fieldsAndValues[$fieldName] = $fieldValue;
                        }
                    }
                }
            }
            else
            {
                $this->killChaining = true;
                $this->lastError    = "";
            }
            return $this;
        }
    }

    // Execute update
    public function execute()
    {
        if ($this->killChaining) return false;
        else
        {

            if (!empty($this->fieldsAndValues))
            {
                $sql = $this->buildSql();
                if ($this->dbObject && (!empty($sql)))
                {
                    $this->dbObject->rawQuery($sql);
                    $affectedRows = $this->dbObject->affectedRows();
                    if ($affectedRows > -1)
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
                else
                {
                    return $sql;
                }
            }
            else
            {
                $this->killChaining = true;
                $this->lastError    = 'No values to update';
            }
        }
    }

    // Build sql for update
    private function buildSql()
    {
        $sql = 'UPDATE '.$this->tableName;
        $setList= array();
        foreach ($this->fieldsAndValues as $field => $value)
        {
            $setList []= $field.' = '.$value;
        }
        $sql.= ' SET '.implode(',', $setList);
        if (!empty($this->filter))
        {
            $sql .= ' WHERE '.$this->filter;
        }
        return $sql.';';
    }

}
?>